package com.lucher.mes.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.lucher.mes.common.Tools;
import com.lucher.mes.controller.BaseController;
import com.lucher.mes.dao.BomMapper;
import com.lucher.mes.dao.ProduceinfoMapper;
import com.lucher.mes.dao.ProducematerialMapper;
import com.lucher.mes.dao.ProductMapper;
import com.lucher.mes.dao.WorklineMapper;
import com.lucher.mes.po.Bom;
import com.lucher.mes.po.Coderule;
import com.lucher.mes.po.Operator;
import com.lucher.mes.po.Produceinfo;
import com.lucher.mes.po.Producematerial;
import com.lucher.mes.po.Product;
import com.lucher.mes.po.Workline;
import com.lucher.mes.service.ICoderuleService;
import com.lucher.mes.service.IProduceinfoService;

/**
 * @Title ProductdepotServiceImpl.java
 * @version 1.0 编码规则类
 */
@Service("produceinfoService")
public class ProduceinfoServiceImpl extends BaseController implements IProduceinfoService {
	@Autowired
    private DataSourceTransactionManager txManager;
	@Autowired
	private ProductMapper productDao;
	@Autowired
	private BomMapper bomDao;
	@Autowired
	private WorklineMapper worklineDao;
	@Autowired
	private ICoderuleService coderuleService;
	@Autowired
	private ProduceinfoMapper produceinfoDao;
	@Autowired
	private ProducematerialMapper producematerialDao;
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];   
	
    /**
	 * 保存生产信息
	 * 
	 * @param String
	 * @return
	 */
	public Map<String, Object> saveProduceinfo(Produceinfo form) {
		//加锁
		synchronized(lock) {
				
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			Map<String, Object> responseMap = new HashMap<String, Object>();
			try{
				responseMap.put("flag", "0");//保存失败
				
				//操作员
				Operator operator = (Operator)getSession().getAttribute("Operator");
				form.setOperator(operator);
				
				if(StringUtils.isEmpty(form.getProductcode())){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，请选择产品编码");
					//回滚
					txManager.rollback(status);
					return responseMap;
					
				}
				Product product = productDao.findByProductcode(form.getProductcode());
				if(product == null){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，产品编码不存在");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				if(form.getAmount() < 1){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，生产数量不能少于1");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				if(StringUtils.isEmpty(form.getLinecode())){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，请选择生产产线");
					//回滚
					txManager.rollback(status);
					return responseMap;
					
				}
				Workline workline = worklineDao.findByCode(form.getLinecode());
				if(workline == null){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，该产线不存在");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				//生产批次号
				String producecode = coderuleService.getSystemcodenoByCodetypeStr(Coderule.CODETYPE_producecode);
				form.setProducecode(producecode);
				
				//当前时间
				String currenttime = Tools.getCurrentTime();
				//订户信息
				form.setProductcode(product.getProductcode());
				form.setProductname(product.getProductname());
				form.setOperatorcode(operator.getLoginname());
				form.setAddtime(currenttime);
				form.setLinename(workline.getName());
				form.setStatus("新建");
				form.setOutamount(0);
				form.setOutstatus("未完成");
				
				//保存生产信息
				produceinfoDao.insertSelective(form);
				
				//生产材料列表
				Bom bomform = new Bom();
				bomform.setProductcode(form.getProductcode());
				List<Bom> bomlist = bomDao.findByList(bomform);
				
				for (int i = 0; i < bomlist.size(); i++) {
					//初始化生产材料表
					Producematerial producematerial = new Producematerial();
					producematerial.setProducecode(producecode);
					producematerial.setProductcode(bomlist.get(i).getProductcode());
					producematerial.setProductname(bomlist.get(i).getProductname());
					producematerial.setMaterialcode(bomlist.get(i).getMaterialcode());
					producematerial.setMaterialname(bomlist.get(i).getMaterialname());
					producematerial.setAmount((bomlist.get(i).getAmount() * form.getAmount()));
					producematerial.setPeramount(bomlist.get(i).getAmount());
					producematerial.setOutamount(0);
					producematerial.setStatus("未完成");
					producematerialDao.insertSelective(producematerial);
				}
				
				//事务提交
				txManager.commit(status);
				
				responseMap.put("flag", "1");//保存失败
				responseMap.put("msg", "操作成功");//
				return responseMap;
			}catch(Exception e){
				
				e.printStackTrace();
				
				//回滚
				txManager.rollback(status);
				
				responseMap.put("flag", "0");//保存失败
				responseMap.put("msg", "数据异常，操作失败");//
				return responseMap;
			}
		} 	
	} 
	
	/**
	 * 修改生产信息
	 * 
	 * @param String
	 * @return
	 */
	public Map<String, Object> updateProduceinfo(Produceinfo form) {
		//加锁
		synchronized(lock) {
				
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			Map<String, Object> responseMap = new HashMap<String, Object>();
			try{
				responseMap.put("flag", "0");//保存失败
				
				Produceinfo produceinfo = produceinfoDao.selectByPrimaryKey(form.getId());
				if(produceinfo == null){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，该生产任务不存在！");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				if(!"新建".equals(produceinfo.getStatus())){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，该生产任务不是新建状态");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				//操作员
				Operator operator = (Operator)getSession().getAttribute("Operator");
				form.setOperator(operator);
				
				if(StringUtils.isEmpty(form.getProductcode())){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，请选择产品编码");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				Product product = productDao.findByProductcode(form.getProductcode());
				if(product == null){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，产品编码不存在");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				if(form.getAmount() < 1){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，生产数量不能少于1");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				if(StringUtils.isEmpty(form.getLinecode())){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，请选择生产产线");
					//回滚
					txManager.rollback(status);
					return responseMap;
					
				}
				Workline workline = worklineDao.findByCode(form.getLinecode());
				if(workline == null){
					responseMap.put("flag", "0");//保存失败
					responseMap.put("msg", "操作失败，该产线不存在");
					//回滚
					txManager.rollback(status);
					return responseMap;
				}
				
				//订户信息
				form.setProductname(product.getProductname());
				form.setLinename(workline.getName());
				
				//保存生产信息
				produceinfoDao.updateByPrimaryKeySelective(form);
				
				//删除旧材料
				producematerialDao.deleteByProducecode(produceinfo.getProducecode());
				
				//添加新的生产材料列表
				Bom bomform = new Bom();
				bomform.setProductcode(form.getProductcode());
				List<Bom> bomlist = bomDao.findByList(bomform);
				
				for (int i = 0; i < bomlist.size(); i++) {
					//初始化生产材料表
					Producematerial producematerial = new Producematerial();
					producematerial.setProducecode(produceinfo.getProducecode());
					producematerial.setProductcode(bomlist.get(i).getProductcode());
					producematerial.setProductname(bomlist.get(i).getProductname());
					producematerial.setMaterialcode(bomlist.get(i).getMaterialcode());
					producematerial.setMaterialname(bomlist.get(i).getMaterialname());
					producematerial.setAmount((bomlist.get(i).getAmount() * form.getAmount()));
					producematerial.setPeramount(bomlist.get(i).getAmount());
					producematerial.setOutamount(0);
					producematerial.setStatus("未完成");
					producematerialDao.insertSelective(producematerial);
				}
				
				//事务提交
				txManager.commit(status);
				
				responseMap.put("flag", "1");//保存失败
				responseMap.put("msg", "操作成功");//
				return responseMap;
			}catch(Exception e){
				
				e.printStackTrace();
				
				//回滚
				txManager.rollback(status);
				
				responseMap.put("flag", "0");//保存失败
				responseMap.put("msg", "数据异常，操作失败");//
				return responseMap;
			}
		} 	
	} 
	
}
